package com.itheima.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.domain.Book;
import com.itheima.service.IBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.xml.transform.Result;
import java.util.List;


@RestController
@RequestMapping("/books")
public class BookController {

    @Autowired
    private IBookService service;

    /**
     * 查询所有
     * @return
     */
    @GetMapping
    public ResultType selectAll(){

        List<Book> list = service.list();
        Integer code=list!=null?Code.GET_OK:Code.GET_ERR;
        String msg=list!=null?"":"数据查询失败，请联系后端人员";
        return new ResultType(code,list,msg);
    }


    /**
     * 添加操作
     * @param book
     * @return
     */
    @PostMapping
    public ResultType insert(@RequestBody Book book){
        boolean save = service.save(book);
        return new ResultType(save?Code.SAVE_OK:Code.SAVE_ERR,save);
    }

    /**
     * 删除操作
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public ResultType deleteById(@PathVariable Integer id){
        boolean b = service.removeById(id);
        return new ResultType(b?Code.UPDATE_OK:Code.UPDATE_ERR,b);
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public ResultType selectById(@PathVariable Integer id){
        Book book = service.getById(id);
        Integer code=book!=null?Code.GET_OK:Code.GET_ERR;
        String msg=book!=null?"":"数据查询失败，请联系后端人员";
        return new ResultType(code,book,msg);
    }


    /**
     * 根据id修改
     * @param
     * @return
     */
    @PutMapping
    public ResultType updateById(@RequestBody Book book){
        boolean b = service.updateById(book);
        return new ResultType(b?Code.UPDATE_OK:Code.UPDATE_ERR,b);
    }

    /**
     * 分页查询，这里本来应该返回page对象里面的数据，而不是page对象
     * 但是page对象里面除了有当前页的数据，还有其他一些信息，推荐返回page对象
     * @param current
     * @param PageSize
     * @return
     */
    @GetMapping("/{current}/{PageSize}")
    public IPage<Book> updateById(@PathVariable Integer current ,@PathVariable Integer PageSize){
        IPage<Book> page=new Page<>(current,PageSize);
        service.page(page);
        Integer code= page!=null?Code.GET_OK:Code.GET_ERR;
        String msg= page!=null?"":"查询错误，请联系后端人员";
        return page;
    }
}
